package com.hz.house.utils.SMS;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hz.house.common.ResultBean;
import com.hz.house.common.ResultUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 获取短息验证码
 */
@RestController
@RequestMapping("api/v2/GetSMSCode")
@Api("获取短息验证码")
public class SendSMS {

    @Autowired
    private SmsSendUtils smsSendUtils;

    @Autowired
    private RedisTemplate<String, Object> redis;


    @GetMapping("getSmsCode")
    @ApiOperation("获取短信验证码")
    public ResultBean getSmsCode(String phoneNum) {

        // 生成6位随机验证码
        String code = getNumberCode();
        // 发送短信
        Map<String, Object> map;
        try {
            map = smsSendUtils.send(phoneNum, code);
        } catch (Exception e) {
            return ResultUtil.fail("短信发送失败！");
        }
        if ("Success".equals(map.get("returnstatus"))) {
            // 将发送成功的短信验证码存入缓存,2分钟过期
            redis.opsForValue().set(phoneNum,code,60 * 2, TimeUnit.SECONDS);
            System.out.println("验证码.........." + code);
            return ResultUtil.ok();
        }
        return ResultUtil.fail("短信发送失败！");
    }

    private String getNumberCode() {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            buf.append((int) (9 * Math.random()));
        }
        return buf.toString();
    }
}